package com.personal.test.orm;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * 文件操作工具类
 * description
 * @author cuibo
 */
public class FileUtil
{


    public static byte[] readInputStream(InputStream in) throws IOException
    {
        if (in == null)
        {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeStream(in, out);
        return out.toByteArray();
    }
    
    public static boolean writeStream(InputStream inputStream, OutputStream outputStream) throws IOException
    {
        if (inputStream == null || outputStream == null)
        {
            return false;
        }

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try
        {
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(outputStream);

            byte[] buffer = new byte[102400];
            int len;

            while ((len = bis.read(buffer)) > 0)
            {
                bos.write(buffer, 0, len);
            }
        } finally
        {
            FileUtil.release(bis);
            FileUtil.release(bos);
            FileUtil.release(inputStream);
            FileUtil.release(outputStream);
        }
        return true;
    }

    
    /**
     * 关闭输入流
     * @param rs 输入流
     *
     */
    public static void release(InputStream rs)
    {
        if (rs != null)
        {
            try
            {
                rs.close();
            } catch (Exception e)
            {
                rs = null;
                e.printStackTrace();
            }
        }

    }

    /**
     * 关闭输出流
     * @param rs 输出流
     *
     */
    public static void release(OutputStream rs)
    {
        if (rs != null)
        {
            try
            {
                rs.close();
            } catch (Exception e)
            {
                rs = null;
                e.printStackTrace();
            }
        }

    }


}
